<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>画板</title>
    <style>
        *{
            user-select: none;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="600" height="300" style="background-color:black"></canvas><br />
    画笔颜色： <input type="color" id="color" /> <br /><br />
    背景颜色： <input type="color" id="back" /> <br /><br />
    画笔粗细： <input type="number" id="line" value="4" min="1" max="100" /><br /> <br />
    <button id="exportBtn">导出图片</button>
</body>
</html>
<script>
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var oldX = 0, oldY = 0;
    var lineColor = 'white';
    var lineWidth = 4;
    var isDraw = false;
    
    // 设置Canvas尺寸
    canvas.width = 600;
    canvas.height = 300;

    canvas.addEventListener('mousedown', down, false);
    canvas.addEventListener('mouseup', up, false);
    canvas.addEventListener('mousemove', move, false);
    canvas.addEventListener('mouseout', up, false); // 鼠标移出Canvas时结束绘制

    function down(e) {
        e.preventDefault();
        oldX = e.pageX - canvas.getBoundingClientRect().left;
        oldY = e.pageY - canvas.getBoundingClientRect().top;
        isDraw = true;
    }

    function up(e) {
        e.preventDefault();
        isDraw = false;
    }

    function move(e) {
        e.preventDefault();
        if (isDraw) {
            var newX = e.pageX - canvas.getBoundingClientRect().left;
            var newY = e.pageY - canvas.getBoundingClientRect().top;
            
            ctx.beginPath();
            ctx.moveTo(oldX, oldY);
            ctx.lineTo(newX, newY);
            ctx.lineWidth = lineWidth;
            ctx.strokeStyle = lineColor;
            ctx.lineCap = 'round';
            ctx.stroke();
            ctx.closePath();
            
            oldX = newX;
            oldY = newY;    
        }
    }

    var colorInput = document.getElementById('color');
    var backInput = document.getElementById('back');
    var lineInput = document.getElementById('line');

    colorInput.onchange = function() {
        lineColor = this.value;
    }

    backInput.onchange = function() {
        canvas.style.backgroundColor = this.value;
    }

    lineInput.onchange = function() {
        lineWidth = parseInt(this.value);
    }

    // 导出图片功能
    document.getElementById('exportBtn').addEventListener('click', function() {
        var link = document.createElement('a');
        link.download = 'canvas-drawing.png';
        link.href = canvas.toDataURL('image/png');
        link.click();
    });
</script>